package cn.i7baozh.consumer.nacos.controller;

import cn.i7baozh.api.entities.CommonResult;
import cn.i7baozh.consumer.nacos.service.PaymentService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Title:
 * @Description:
 * @author: baoqi.zhang
 * @date: 2022/4/13 15:18
 */
@Slf4j
@RestController
public class OrderNacosController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String port;

    @SentinelResource(value = "consumerParam", fallback = "fallback", blockHandler = "blockHandler")
    @GetMapping("/consumer/nacos/param/{name}/{path}")
    public CommonResult<String> consumerParam(@PathVariable(value = "name", required = false) String  name,
                                            @PathVariable(value = "path", required = false) String  path ) {
        log.info("hot port:{}", port);
        return new CommonResult<>(200,"成功", paymentService.abc());
    }

    @SentinelResource(value = "consumerHot", fallback = "fallback", blockHandler = "blockHandler")
    @GetMapping("/consumer/nacos/hot")
    public CommonResult<String> consumerHot(@RequestParam(value = "id", required = false) Integer id) {
        log.info("hot port:{}", port);
        return new CommonResult<>(200,"成功", paymentService.abc());
    }
    @SentinelResource(value = "consumerABC", fallback = "fallback", blockHandler = "blockHandler")
    @GetMapping("/consumer/nacos/abc/{id}")
    public CommonResult<String> getAbc(@PathVariable(value = "id") Integer id) {
        log.info("abc port:{}", port);
        if (id == 1) {
            throw new IllegalArgumentException("非法参数");
        } else if (id == 2) {
            throw new NullPointerException("空指针");
        }
        return new CommonResult<>(200,"成功", paymentService.abc());
    }

    public CommonResult<String> fallback(@PathVariable(value = "id") Integer id, Throwable t) {

        return new CommonResult<>(201,"内部错误-降级方法:" + t.getMessage() + " 参数 " + id);
    }

    public CommonResult<String> blockHandler(@PathVariable(value = "id") Integer id, BlockException blockException) {

        return new CommonResult<>(202,"限流了:" + blockException.getMessage() + " 参数 " + id);
    }
}
